﻿using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Xml.Linq;
using Knetlik.Models.LocalExtensions;

namespace Knetlik.Models
{
    public class SessionsList
    {
        public static List<Session> Instance = ReadSessions();

        private static List<Session> ReadSessions()
        {
            var result = new List<Session>();

            string path = Path.Combine(HttpContext.Current.Server.MapPath("."), "App_Data\\Sessions.xml");
            var doc = XDocument.Load(path);

            if (doc.Root != null) {
                foreach (var elSession in doc.Root.Elements()) {
                    var elSpeaker = elSession.GetNested("speaker");

                    var session = new Session {
                        Time = elSession.Read("time"),
                        Topic = elSession.Read("topic"),
                        Description = elSession.Read("description"),
                        Speaker = new Speaker {
                            Name = elSpeaker.Read("name"),
                            Photo = elSpeaker.Read("photo"),
                            Bio = elSpeaker.Read("bio")
                        }
                    };
                    result.Add(session);
                }
            }

            return result;
        }

        public static void UpdateList()
        {
            Instance = ReadSessions();
        }
    }

    namespace LocalExtensions
    {
        internal static class Extensions
        {
            /// <summary>
            /// Reads data from the given XML element.
            /// </summary>
            /// <param name="element">Element to get the data from.</param>
            /// <param name="dataSource">Name of the data source: either attribute or nested XML element.</param>
            /// <returns></returns>
            internal static string Read(this XElement element, string dataSource)
            {
                var attribute = element.Attribute(dataSource);
                if (attribute != null)
                    return attribute.Value;
                
                foreach (var item in element.Elements()) {
                    if (item.Name == dataSource) {
                        return item.Value;
                    }
                }

                return "undefined";
            }

            internal static XElement GetNested(this XElement element, string subElementName)
            {
                foreach (var item in element.Elements()) {
                    if (item.Name == subElementName)
                        return item;
                }

                return new XElement("Undefined");
            }
        }
    }
}
